
use std::collections::HashMap;

use reqwest::header::{HeaderMap,  HeaderValue};
use serde_json::Value; 

use super::super::my_err::MyErr;  

impl super::Aliyun {


    /// 发送模板短信
    /// phone_numbers 手机号码，多个号码用半角 （,） 号隔开，如 13800138000 或 13800138000,13700137000
    /// sign_name 签名，必须是已经在阿里云上申请好的签名，如："拓程科技"
    /// template_code 短信模板编号, 如：SMS_473320332
    /// template_param 短信模板对应的内容json字符串，如：{\"name\":\"1234+321\",\"date\":\"1234\",\"money\":\"1234\"}
    ///
    /// ```
    /// let aliyun : crate::mylib::aliyun::Aliyun = crate::mylib::aliyun::Aliyun::new_config();
    ///
    /// let phone_numbers =  "18677667550";
    /// let sign_name =  "拓程科技";
    /// let template_code =  "SMS_473320332";
    /// let template_param =  "{\"name\":\"1234+321\",\"date\":\"1234\",\"money\":\"1234\"}";
    ///
    /// let _ = aliyun.send_sms(phone_numbers, sign_name, template_code, template_param).await;
    /// ```
    #[allow(dead_code)]
    pub async fn send_sms(&self, phone_numbers: &str, sign_name: &str, template_code: &str, template_param: &str) -> Result<bool, MyErr> {
        let method = reqwest::Method::GET;
        let content_type = super::CONTENT_TYPE_URL;
        let canonical_uri = "/";
        let host = "dysmsapi.aliyuncs.com";
        let x_acs_action = "SendSms";
        let x_acs_version = "2017-05-25";

        // 数据头
        let mut headers = HeaderMap::new();
        headers.insert("x-acs-action", HeaderValue::from_static(x_acs_action));
        headers.insert("x-acs-version", HeaderValue::from_static(x_acs_version));
        headers.insert("host", HeaderValue::from_static(host));
        headers.insert("content-type", HeaderValue::from_static(content_type));

        // url参数
        let mut query_param: HashMap<String, String> = HashMap::new();
        query_param.insert("PhoneNumbers".to_string(), phone_numbers.to_string());
        query_param.insert("SignName".to_string(), sign_name.to_string());
        query_param.insert("TemplateCode".to_string(), template_code.to_string());
        query_param.insert("TemplateParam".to_string(), template_param.to_string());

        let body_string = "".to_string();
        let body_json: serde_json::Map<String, Value> = serde_json::Map::new();
        let body_binary: Vec<u8> = Vec::new();

        let res_json = self
            .request_payload(
                method,
                canonical_uri,
                &mut headers,
                query_param,
                body_string,
                body_json,
                body_binary,
            )
            .await?;

        println!("\n\n {:?} \n\n", res_json);

        let code = res_json.get("Code").and_then(Value::as_str).unwrap_or_default();
        let message = res_json.get("Message").and_then(Value::as_str).unwrap_or_default();

        if code == "OK" {
            Ok(true)
        } else {
            Err(MyErr::Msg(message.to_string()))
        }
    }
}